/**
 * 用户管理脚本
 */
(function() {
	/***************************************************************************
	 * 页面初始化
	 */
	// document.onkeydown = function(e) {
	// platform.forbiddenEnter(e);
	// }
	window.onload = function() {
		userGridView.init();
    };
	/***************************************************************************
	 * userGridView
	 */
	var userGridView = {
		init: function() {
			var columns = [{
				checkbox: true,
				field: 'checkbox',
				align: 'center',
				valign: 'middle'
			}, {
				field: 'user_id',
				title: '主键标识',
				width: 250,
				valign: 'middle',
				align: 'center'
			}, {
				field: 'user_name',
				title: '用户名',
				width: 120,
				valign: 'middle'
			}, {
				field: 'nick_name',
				title: '显示名称',
				width: 200,
				valign: 'middle'
			}, {
				field: 'effective_date',
				title: '生效日期',
				width: 180
			}, {
				field: 'expire_date',
				title: '失效日期',
				width: 120
			}];

			$('#tb_users').bootstrapTable({
				url: platform.mapUrl('~/rest/user/list'),
				cache: false,
				method: 'post',
				contentType: 'application/json',
				dataType: 'json',
				search: false,
				strictSearch: true,
				singleSelect: true,
				striped: true,
				showFooter: false,
				showToggle: false,
				showRefresh: true,
				showPaginationSwitch: false,
				silent: true,
				pagination: true,
				sidePagination: 'server',
				pageNumber: 1,
				pageSize: 10,
				pageList: [10, 15, 20, 50],
				queryParams: function(params) {
					return {
						pageNumber: params.offset / params.limit + 1,
						pageSize: params.limit
					}
				},
				clickToSelect: true,
				height: 504,
				uniqueId: 'user_id',
				userView: false,
				cardView: false,
				toolbar: '#toolbar',
				columns: columns
			}).bootstrapTable('hideColumn', 'user_id');
		},
		fnSearch: function() {
			$("#tb_users").bootstrapTable("refresh", {
				query: {
					nick_name: $("#name").val() == "" ? null : $("#name").val()
				}
			});
		},
		/**
		 * 表单新增
		 */
		fnAdd: function() {
			// 设置标题
			userHeaderView.uv_title('用户基本信息录入');
			// 数据初始化
			userView.clear();
			userView.initForm();
			userView.validateForm();
			$('#userModal').modal('show');
		},
		fnEdit: function() {
			var result = platform.checkSelected('tb_users', 'EDIT');
			if(result) {
				userHeaderView.uv_title('用户基本信息编辑');
				// var selections =
				// $('#tb_users').bootstrapTable('getSelections');
				var form = userView;
				form.clear();
				form.validateForm();
				form.uv_editstatus('1'); // 编辑状态
				form.uv_enabled(true);
			}

		},
		fnRemove: function() {
			// 当前登录用户数据不能删除
			var result = platform.checkSelected('tb_users', 'remove');
			if(result) {
				var selections = $('#tb_users').bootstrapTable('getSelections');
				var param = {};
				param.user_id = selections[0].user_id;
				param.user_name = selections[0].user_name;

				methods.del(param);
			}
		},
		fnView: function() {
			var result = platform.checkSelected('tb_users', 'VIEW');
			if(result) {
				var selections = $('#tb_users').bootstrapTable('getSelections');
				userView.showViewForm(selections[0].user_id);
			}
		}
	};

	ko.applyBindings(userGridView, document.getElementById('userList'));

	/***************************************************************************
	 * userHeaderView
	 */
	var userHeaderView = {
		uv_title: ko.observable()
	};
	ko.applyBindings(userHeaderView, document.getElementById('modalHeader'));

	/***************************************************************************
	 * userView
	 */
	var userView = {
		/**
		 * parameter
		 */
		uv_userid: ko.observable(''), // 默认主键
		uv_username: ko.observable(''), // 用户名
		uv_nickname: ko.observable(''), // 昵称
		uv_password: ko.observable(''), // 密码
		uv_editstatus: ko.observable(''), // 默认数据状态
		uv_recordstatus: ko.observable(''), // 默认数据状态
		uv_enabled: ko.observable(false), // 只读设置
		/**
		 * method
		 */
		/**
		 * 表单初始化，表单新增时使用
		 */
		initForm: function(editstaus) {
			this.uv_userid(platform.uuid());
			this.uv_editstatus('0');
			this.uv_recordstatus('1');
			this.uv_enabled(true);
		},
		clear: function() {
			this.uv_userid('');
			this.uv_username('');
			this.uv_nickname('');
			this.uv_password('');
			this.uv_editstatus('');
			this.uv_recordstatus('');
			this.uv_enabled(false);
		},
		validateForm: function() { // 初始化表单,默认校验规则
			$('#detailForm').bootstrapValidator({
				message: 'This value is not valid',
				feedbackIcons: {
					valid: 'glyphicon glyphicon-ok',
					invalid: 'glyphicon glyphicon-remove',
					validating: 'glyphicon glyphicon-refresh'
				},
				excluded: [':disabled'],
				fields: {
					userName: {
						validators: {
							notEmpty: {
								message: '用户名称为必填字段,不可为空'
							},
							stringLength: {
								min: 5,
								max: 12,
								message: '用户名长度限制在5-12位之间'
							},
							regexp: { /* 只需加此键值对，包含正则表达式，和提示 */
								regexp: /^[a-zA-Z0-9\.]+$/,
								message: '只能是数字、字母.'
							},
							remote: { // onchange校验，不太实用，频繁调用，可用性差，此处保留仅作为测验，可通过使用光标离开事件替代
								url: platform.mapUrl('~/rest/user/validate'),
								message: '检测到用户名已存在',
								type: 'post'
							}
						}
					},
					nickName: {
						validators: {
							notEmpty: {
								message: '用户昵称为必填字段,不可为空'
							}
						}
					},
					userPwd: {
						validators: {
							notEmpty: {
								message: '密码为必填字段,不可为空'
							},
							stringLength: {
								min: 6,
								max: 12,
								message: '密码长度应该控制在6-12位之间'
							}
						}
					}
				}
			});
		},
		resetForm: function() {
			if($('#detailForm').data('bootstrapValidator') != null ||
				$('#detailForm').data('bootstrapValidator') != undefined) {
				$('#detailForm').data('bootstrapValidator').resetForm();
			}
		},
		showViewForm: function(pid) {
			var result = methods.get(pid);
			var form = userView;
			form.clear();
			form.resetForm();
			form.uv_username(result.user_name);
			form.uv_nickname(result.nick_name);
			form.uv_editstatus('2');
			form.uv_enabled(false);
			userHeaderView.uv_title('用户基本信息查看');

			$('#saveBtn').hide();
			$('#userModal').modal('show');
		}
	};
	ko.applyBindings(userView, document.getElementById('detailForm'));

	/***************************************************************************
	 * userFunctionView
	 */
	var userFunctionView = {
		fnSaveForm: function() { // 表单保存操作
			// 进行表单信息校验
			$('#detailForm').data('bootstrapValidator').validate();
			if(!$('#detailForm').data('bootstrapValidator').isValid()) {
				platform.showOperTip('VALIDATEFAIL');
				return;
			}

			var form = userView;
			var param = {};
			param.user_id = form.uv_userid();
			param.user_name = form.uv_username();
			param.nick_name = form.uv_nickname();
			param.user_pwd = CryptoJS.enc.Base64.stringify(CryptoJS.MD5(form
				.uv_password()));
			param.edit_status = form.uv_editstatus();
			param.record_status = form.uv_recordstatus();

			platform.servicebreakAsync('~/rest/user/save', param, 'post',
				function() {
					platform.showOperTip('dealing');
				}).done(function() {
				platform.showOperTip('SAVESUC');
				$('#tb_users').bootstrapTable('refresh');
			});

		},
		fnCloseDlg: function() { // 表单关闭操作
			// 清空数据，确保下次打开时全新而非夹带上次已有数据
			// $('#detailForm').data('bootstrapValidator').destroy();
			userView.resetForm();
			$('input', 'form').attr('readonly');
			$('#userModal').on('hidden.bs.modal', function() {
				$('#userPwd').show();
				$('#saveBtn').show();
			}).modal('hide');
		}
    };
	ko.applyBindings(userFunctionView, document.getElementById('modalFooter'));

	/***************************************************************************
	 * methods
	 */
	var methods = {
		del: function(param) {
			// if (selections[0].user_name == $.cookie('_curUser')) {
			// platform.showErrorTip('已阻止试图删除当前登录用户的操作');
			// return;
			// }
			platform.servicebreakAsync('~/rest/user/delete', param, 'post')
				.done(function(response) {
					if(response.success) {
						platform.showOperTip('DELSUC');
						$('#tb_users').bootstrapTable('refresh');

                    } else {
						platform.showOperTip('DELSUC');

                    }
				});
		},
		get: function(pid) {
			var param = {};
			param.user_id = pid;
			var result = JSON2.parse(platform.servicebreak(
				'~/rest/user/selectOne', param)).result;
			return result;
		},
	}
})(this);